package com.mall.product.service.impl;

import com.alibaba.fastjson2.JSON;
import com.mall.common.dto.SkuReductionDTO;
import com.mall.common.dto.SkuStoreDTO;
import com.mall.common.es.SkuEsModel;
import com.mall.common.utils.Constant;
import com.mall.common.utils.R;
import com.mall.product.dto.SpuBoundsDTO;
import com.mall.product.entity.*;
import com.mall.product.feign.CouponFeignService;
import com.mall.product.feign.EsSearchFeignService;
import com.mall.product.feign.WareSkuStroeFeignService;
import com.mall.product.service.*;
import com.mall.product.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.utils.PageUtils;
import com.mall.common.utils.Query;

import com.mall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {



    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService spuImagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private SpuInfoDao spuInfoDao;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private WareSkuStroeFeignService wareSkuStroeFeignService;

    @Autowired
    private EsSearchFeignService esSearchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {


        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<SpuInfoEntity>();
      String key = (String)  params.get(Constant.KEY);
      if(StringUtils.isNotBlank(key)){
          queryWrapper.like("spu_name",key);
      }
        String brandId =(String)  params.get("brandId");
        if(StringUtils.isNotBlank(brandId) && !"0".equalsIgnoreCase(brandId)){
            queryWrapper.like("brandId",brandId);
        }
        String catelogId =(String)  params.get("catelogId");
        if(StringUtils.isNotBlank(catelogId) && !"0".equalsIgnoreCase(brandId) ){
            queryWrapper.like("catelogId",catelogId);
        }
        String status =(String)  params.get("status");
        if(StringUtils.isNotBlank(status)){
            queryWrapper.like("publish_status",status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),queryWrapper
        );

        return new PageUtils(page);
    }

    @Override
    @Transactional
    public void save(SpuSaveVo spuSaveVo) {

        //  1、保存spu基本信息    pms_spu_info
        SpuInfoEntity spuInfo = new SpuInfoEntity();
        spuInfo.setSpuName(spuSaveVo.getSpuName());
        spuInfo.setSpuDescription(spuSaveVo.getSpuDescription());
        spuInfo.setCatalogId(spuSaveVo.getCatalogId());
        spuInfo.setBrandId(spuSaveVo.getBrandId());
        spuInfo.setWeight(spuSaveVo.getWeight());
        spuInfo.setPublishStatus(0);
        spuInfo.setCreateTime(new Date());
        this.baseMapper.insert(spuInfo);


        // 2、保存spu的描述信息(pms_spu_info_desc)
        SpuInfoDescEntity spuInfoDesc = new SpuInfoDescEntity();
        spuInfoDesc.setSpuId(spuInfo.getId());
        spuInfoDesc.setDecript(String.join(",",spuSaveVo.getDecript()));
        spuInfoDescService.save(spuInfoDesc);


        //3.保存spu的图片集(pms_spu_images)
        List<String> images = spuSaveVo.getImages();
        if(!CollectionUtils.isEmpty(images)){
            List<SpuImagesEntity> imageList = images.stream().map(item->{
                SpuImagesEntity spuImagesEntity = new SpuImagesEntity();
                spuImagesEntity.setSpuId(spuInfo.getId());
                spuImagesEntity.setImgUrl(item);
                return spuImagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(imageList);
        }

        // 4、保存spu的规格参数(pms_product_attr_value)
        List<BaseAttrs> baseAttrs = spuSaveVo.getBaseAttrs();
        if(!CollectionUtils.isEmpty(baseAttrs)){
            List<ProductAttrValueEntity> productAttrValueEntityList = baseAttrs.stream().map(item ->{
                AttrEntity attrEntity = attrService.getById(item.getAttrId());
                ProductAttrValueEntity productAttrValue = new ProductAttrValueEntity();
                productAttrValue.setSpuId(spuInfo.getId());
                productAttrValue.setAttrId(item.getAttrId());
                productAttrValue.setAttrValue(item.getAttrValues());
                productAttrValue.setAttrName(attrEntity.getAttrName());
                productAttrValue.setQuickShow(item.getShowDesc());
                return productAttrValue;
            }).collect(Collectors.toList());
            productAttrValueService.saveBatch(productAttrValueEntityList);
        }

        // 5、保存spu的积分信息  gulimall_sms -> sms_spu_bounds
        Bounds bounds = spuSaveVo.getBounds();
        SpuBoundsDTO spuBoundsDTO = new SpuBoundsDTO();
        spuBoundsDTO.setSpuId(spuInfo.getId());
        spuBoundsDTO.setGrowBounds(bounds.getGrowBounds());
        spuBoundsDTO.setBuyBounds(bounds.getBuyBounds());
         R r = couponFeignService.save(spuBoundsDTO);
        if(!r.get("code").equals("0")){
            log.error("远程保存spu积分信息失败");
        }
        // 6、保存当前spu对应的所有sku信息
        List<Skus> skuList = spuSaveVo.getSkus();
        if(!CollectionUtils.isEmpty(skuList)){

            for(Skus  sku : skuList){
                // 6.1)、sku的基本信息(pms_sku_info)
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                BeanUtils.copyProperties(sku,skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfo.getId());
                skuInfoEntity.setBrandId(spuSaveVo.getBrandId());
                skuInfoEntity.setCatalogId(spuSaveVo.getCatalogId());
                skuInfoEntity.setSaleCount(0L);
                skuInfoEntity.setSkuDefaultImg(sku.getImages().get(0).getImgUrl());
                skuInfoService.save(skuInfoEntity);

                // 6.2)、sku的图片信息(pms_sku_images)
              List<SkuImagesEntity>  skuImagesEntityList = sku.getImages().stream().map(item ->{
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuInfoEntity.getSkuId());
                    skuImagesEntity.setImgUrl(item.getImgUrl());
                    skuImagesEntity.setDefaultImg(item.getDefaultImg());
                    return skuImagesEntity;
                }).filter(skuImage -> StringUtils.isNotBlank(skuImage.getImgUrl())).collect(Collectors.toList());
                skuImagesService.saveBatch(skuImagesEntityList);

                // 6.3)、sku的销售属性信息(pms_sku_sale_attr_value)

              List<Attr> attrList=  sku.getAttr();
              if(!CollectionUtils.isEmpty(attrList)){
                List<SkuSaleAttrValueEntity>  skuSaleAttrValueEntityList = attrList.stream().map(item->{
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(item,skuSaleAttrValueEntity);
                      skuSaleAttrValueEntity.setSkuId(skuInfoEntity.getSkuId());
                      return skuSaleAttrValueEntity;
                  }).collect(Collectors.toList());
                  skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntityList);
              }
              // 6.4)、sku的优惠、满减等信息   gulimall_sms -> sms_sku_ladder/sms_sku_full_reduction/sms_member_price
                SkuReductionDTO skuReductionDTO = new SkuReductionDTO();
                BeanUtils.copyProperties(sku, skuReductionDTO);
                skuReductionDTO.setMemberPrice(sku.getMemberPrice());
                skuReductionDTO.setSkuId(skuInfoEntity.getSkuId());
                couponFeignService.saveSkuReduction(skuReductionDTO);

            }
        }
    }

    @Override
    public R spuUp(Long spuId) {

        //构造ES保存 spu 上架数据

        //查询spu基本信息
       SpuInfoEntity spuInfoEntity = spuInfoDao.selectById(spuId);

        //构造 brandName  categoryName
       BrandEntity brandEntity = brandService.getById(spuInfoEntity.getBrandId());
       CategoryEntity categoryEntity = categoryService.getById(spuInfoEntity.getCatalogId());

       //狗仔sku基本信息 到 SpuEsModel中
      List<SkuInfoEntity>  skuInfoEntityList = skuInfoService.querySkuInfoBySpuId(spuId);

      //根据spu找出所有sku库存数据
        List<Long> skuIdList = skuInfoEntityList.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());


      List<SkuStoreDTO>   skuStoreDTOList = wareSkuStroeFeignService.queryStoreInfo(skuIdList);
      Map<Long,Long> skuStoreMap =  skuStoreDTOList.stream().collect(Collectors.toMap(SkuStoreDTO::getSkuId, SkuStoreDTO::getStoreCount));


      List<SkuEsModel.Attr> attrList = productAttrValueService.queryAttrInfoBySpuId(spuId);


       List<SkuEsModel>  skuEsModelList = skuInfoEntityList.stream().map(item ->{
            SkuEsModel spuEsModel =  new SkuEsModel();
            BeanUtils.copyProperties(item,spuEsModel);
            //构造 brandName brandImg categoryName
            spuEsModel.setBrandImg(brandEntity.getLogo());
            spuEsModel.setBrandName(brandEntity.getName());
            spuEsModel.setCatalogName(categoryEntity.getName());
            //构造价钱
            spuEsModel.setSkuPrice(item.getPrice());
            spuEsModel.setSkuImg(item.getSkuDefaultImg());
            spuEsModel.setHotScore(0L);
            // private boolean hasStock;        List<SkuEsModel.Attr> attrs;
            spuEsModel.setHasStock(skuStoreMap.get(item.getSkuId())==null?false:skuStoreMap.get(item.getSkuId())>0);

            //构造ListAttr
            spuEsModel.setAttrs(attrList);

            return spuEsModel;
        }).collect(Collectors.toList());

        //发送数据给 ES skuEsModelList
      R r =  esSearchFeignService.saveProductIndex(skuEsModelList);
    Integer code =(Integer) r.get("code");

      if(code == 0){
          //es上架成功 修改商品状态为上架状态
         // spuInfoDao.update
          spuInfoDao.updatePulishStatus(1,spuId);
          return R.ok();
      }else{
          return R.error();
      }


    }

}